package cn.school.servlet;

import cn.school.entity.Subject;
import cn.school.service.SubjectService;
import cn.school.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/addSubjectServlet")
public class AddSubjectServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Long gid= StringUtil.toLong(request.getParameter("gradeid"));
        int classhour=StringUtil.toInt(request.getParameter("classhour"));
        String subjectname=request.getParameter("subjectname");
        Subject sub=new Subject();
        sub.setClasshour(classhour);
        sub.setGradeId(gid);
        sub.setSubjectname(subjectname);
        int res = SubjectService.INST.add(sub);
        if(res<1)
            response.getWriter().print("add failed");
        else
        {
            //response.getWriter().print("add successful");
            //request.getRequestDispatcher("/subjectServlet").forward(request,response);
            // response.sendRedirect("subjectServlet");//重定向，一般不加  /
            //中文乱码
            //response.sendRedirect("subjectServlet?subjectname="+subjectname);
            response.sendRedirect("subjectServlet?subjectname="+ URLEncoder.encode(subjectname,"utf-8"));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
